package com.yiwei.hdb.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.allen.library.SuperButton;
import com.yiwei.hdb.R;
import com.yiwei.hdb.activity.Application;
import com.yiwei.hdb.activity.CodeVerifyActivity;
import com.yiwei.hdb.activity.MainActivityNew;
import com.yiwei.hdb.activity.PermissionActivity;
import com.yiwei.hdb.activity.ServiceFeePayActivity;
import com.yiwei.hdb.activity.V3FaceIdentityOneActivity;
import com.yiwei.hdb.activity.V3IdcardIdentityActivity;
import com.yiwei.hdb.activity.WechatChatActivity;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.event.ChangeHomePagerEvent;
import com.yiwei.hdb.event.SelectMoneyEvent;
import com.yiwei.hdb.model.V3HomeIndexModel;
import com.yiwei.hdb.util.DisplayUtil;
import com.yiwei.hdb.util.Network;
import com.yiwei.hdb.util.PreferenceUtils;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.Dialog;
import com.yiwei.hdb.view.FastViewPager;
import com.yiwei.hdb.view.ObservableScrollView;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-11-1.
 */

public class FragmentHomeV4 extends BaseFragment implements ObservableScrollView.ScrollViewListener {
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.img_step)
    ImageView imgStep;
    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.layout_login)
    LinearLayout layoutLogin;
    @BindView(R.id.txt_notice)
    ViewFlipper txtNotice;
    @BindView(R.id.pager_one)
    FastViewPager pagerOne;
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    Unbinder unbinder;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.txt_service_fee)
    TextView txtServiceFee;
    @BindView(R.id.btn_service_fee)
    SuperButton btnServiceFee;
    @BindView(R.id.layout_has_service)
    LinearLayout layoutHasService;
    @BindView(R.id.layout_no_service)
    LinearLayout layoutNoService;
    @BindView(R.id.btn_invite)
    ImageView btnInvite;
    private int currentPage = 0;
    private mTouchListener touchListener;
    public String loanType = "1";
    private boolean isGetData = false;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home_v4;
    }

    @Override
    protected void initView() {
        scrollView.setScrollViewListener(this);

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getIndex();
            }
        });
        pagerOne.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                if (position == pagerOne.getChildCount() - 1) {
                    if (touchListener == null) {
                        touchListener = new mTouchListener();
                    }
                    pagerOne.setOnTouchListener(touchListener);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    public void getIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getV3HomeIndex().compose(RxLifeUtil.checkOn(getContext())).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);

                    } catch (NullPointerException e) {

                    }

                }).
                subscribe(result -> {
                    setData(result.data);

                });
    }

    private void setData(V3HomeIndexModel.DataBean data) {


        //0：失败、1：走新申请流程、2：继续上次未完成的流程、3：申请审核中、4：申请未通过、5：等待放款、6：还款中
        if (data.deal_status != null) {
            deal_id = data.deal_status.deal_id;
            UserGlobal.setDealId(data.deal_status.deal_id);

            StringBuilder builder = new StringBuilder();
            if (data.deal_status.remark_text != null && data.deal_status.remark_text.size() != 0) {

                for (int i = 0; i < data.deal_status.remark_text.size(); i++) {
                    builder.append(data.deal_status.remark_text.get(i));
                }

            }


            if (TextUtils.isEmpty(data.deal_status.status)) {
                loanType = "0";
            } else {
                loanType = data.deal_status.status;
            }

            if (UserGlobal.checkLogin()) {
                layoutLogin.setVisibility(View.VISIBLE);
                txtInfoRight.setVisibility(View.GONE);
                imgStep.setVisibility(View.GONE);
            } else {
                layoutLogin.setVisibility(View.GONE);
                imgStep.setVisibility(View.VISIBLE);
            }


            DecimalFormat df = new DecimalFormat("#.00");
            if (data.user.deal_max_quota != null) {
                data.user.deal_max_quota = df.format(Double.valueOf(data.user.deal_max_quota));
            }
            if (data.deal_status.money != null) {
                data.deal_status.money = df.format(Double.valueOf(data.deal_status.money));
            }

            layoutNoService.setVisibility(View.VISIBLE);
            layoutHasService.setVisibility(View.GONE);
            switch (loanType) {
                case "0":
                    txtMoney.setText(data.user.deal_max_quota);
                    txtMoney.setTextColor(0xff00C3BE);
                    imgStatus.setImageResource(R.mipmap.img_home_default_bg);
                    if (UserGlobal.checkLogin()) {
                        btnSubmit.setText("立即下款");
                        txtInfoRight.setVisibility(View.VISIBLE);
                    } else {
                        btnSubmit.setText("注册/登录");
                    }
                    txtInfoLeft.setText("想要更高额度？做认证丶提额度，借的更多~");

                    btnSubmit.setShapeGradientStartColor(0xff3EE7E4).setShapeGradientEndColor(0xff00CAC5).setUseShape();
                    txtTips.setText("最高可申请额度");

                    break;
                case "1":
                    txtMoney.setText(data.user.deal_max_quota);
                    txtMoney.setTextColor(0xff00C3BE);
                    if (UserGlobal.checkLogin()) {
                        btnSubmit.setText("立即下款");
                        txtInfoRight.setVisibility(View.VISIBLE);
                    } else {
                        btnSubmit.setText("注册/登录");
                    }
                    txtInfoLeft.setText("想要更高额度？做认证丶提额度，借的更多~");
                    btnSubmit.setShapeGradientStartColor(0xff3EE7E4).setShapeGradientEndColor(0xff00CAC5).setUseShape();
                    txtTips.setText("最高可申请额度");
                    imgStatus.setImageResource(R.mipmap.img_home_default_bg);

                    break;
                case "2":
                    txtMoney.setText(data.user.deal_max_quota);
                    txtMoney.setTextColor(0xff00C3BE);
                    if (UserGlobal.checkLogin()) {
                        btnSubmit.setText("立即下款");
                        txtInfoRight.setVisibility(View.VISIBLE);
                    } else {
                        btnSubmit.setText("注册/登录");
                    }
                    txtInfoLeft.setText("想要更高额度？做认证丶提额度，借的更多~");
                    btnSubmit.setShapeGradientStartColor(0xff3EE7E4).setShapeGradientEndColor(0xff00CAC5).setUseShape();
                    txtTips.setText("最高可申请额度");
                    imgStatus.setImageResource(R.mipmap.img_home_default_bg);

                    break;
//                申请审核中
                case "3":
                    txtMoney.setText(data.deal_status.money);
                    txtMoney.setTextColor(0xffFBAB49);
                    imgStatus.setImageResource(R.mipmap.img_home_shenhe);
                    txtTips.setText("已申请借款金额");
                    txtInfoLeft.setText("您的借款申请已经提交成功，请耐心等待工作人员审核，如有疑问，请及时联系客服。");
                    btnSubmit.setText("审核中");
                    btnSubmit.setShapeGradientStartColor(0xffFDD190).setShapeGradientEndColor(0xffFBAB49).setUseShape();
                    break;
//                申请未通过
                case "4":
                    txtMoney.setText(data.deal_status.money);
                    txtMoney.setTextColor(0xffC0C0C0);
                    imgStatus.setImageResource(R.mipmap.img_home_fail);
                    txtTips.setText("我的可用额度");
                    txtInfoLeft.setText("很遗憾!您的借款申请未通过完善一下认证信息，过段时间再来吧！");
                    btnSubmit.setText("完善信息");
                    btnSubmit.setShapeGradientStartColor(0xffE9E9E9).setShapeGradientEndColor(0xffC0C0C0).setUseShape();
                    if (UserGlobal.isShowDealDialog(data.deal_status.deal_id)) {
                        Dialog.showCheckFail(getContext(), new Dialog.DialogClickListener() {
                            @Override
                            public void confirm() {
                                EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                            }
                        });
                    }

                    break;
//                等待放款
                case "5":
                    txtMoney.setText(data.deal_status.money);
                    txtMoney.setTextColor(0xff75BAFE);
                    imgStatus.setImageResource(R.mipmap.img_home_fangkuan);
                    txtTips.setText("已申请借款金额");
                    txtInfoLeft.setText("您的借款申请正在放款中，借款稍后将转入您绑定的银行卡，请注意查收");
                    btnSubmit.setText("放款中");
                    btnSubmit.setShapeGradientStartColor(0xffA3D4FF).setShapeGradientEndColor(0xff75BAFE).setUseShape();
                    break;
//                还款中
                case "6":
                    txtMoney.setText(data.deal_status.money);
                    if (data.deal_status.overdue_days > 0) {
                        txtMoney.setTextColor(0xffFF6D74);
                        imgStatus.setImageResource(R.mipmap.img_home_yuqi);
                        btnSubmit.setShapeGradientStartColor(0xffFF8E93).setShapeGradientEndColor(0xffFF6D74).setUseShape();
                    } else {
                        txtMoney.setTextColor(0xff759CFE);
                        imgStatus.setImageResource(R.mipmap.img_home_huankuan);
                        btnSubmit.setShapeGradientStartColor(0xffA3BDFF).setShapeGradientEndColor(0xff759CFE).setUseShape();
                    }
                    txtTips.setText("近期待还金额");
                    btnSubmit.setText("立即还款");
                    txtInfoLeft.setText(builder.toString());
                    break;
                case "7":
                    layoutNoService.setVisibility(View.GONE);
                    layoutHasService.setVisibility(View.VISIBLE);
                    txtServiceFee.setText(data.deal_status.services_fee);

                    break;

            }


            pagerOne.setPageMargin(DisplayUtil.dip2px(getContext(), 15));
            pagerOne.setAdapter(new PagerOneAdapter(getChildFragmentManager(), data.deal_user_list));


        }


        if (data.notice != null && data.notice.size() != 0 && !isGetData) {
            if (txtNotice.getChildCount() != 0) {
                txtNotice.removeAllViews();
            }
            for (int i = 0; i < data.notice.size(); i++) {
                LinearLayout layout = (LinearLayout) View.inflate(getContext(), R.layout.item_home_notice, null);
                TextView txtLeft = (TextView) layout.findViewById(R.id.txt_left);
                txtLeft.setText(data.notice.get(i).text);
                TextView txtRight = (TextView) layout.findViewById(R.id.txt_right);
                txtRight.setText(data.notice.get(i).time);
                txtNotice.addView(layout);
            }
        }

        isGetData = true;
    }

    private String deal_id;

    @OnClick(R.id.btn_service_fee)
    public void onViewClicked() {
        Intent intent = new Intent(getContext(), ServiceFeePayActivity.class);
        intent.putExtra("deal_id", deal_id);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
    }

    @OnClick(R.id.btn_invite)
    public void onViewClicked1() {
        if (Util.checkLogin(getActivity()))
            EventBus.getDefault().post(new ChangeHomePagerEvent(2));
    }

    public class PagerOneAdapter extends FragmentPagerAdapter {

        //        String[] tabs = {"未还账单", "还款记录"};
        private List<Fragment> fragments = new ArrayList<>();

        public PagerOneAdapter(FragmentManager fm, List<V3HomeIndexModel.DataBean.DealUserListBean> item) {
            super(fm);
            fragments.clear();
            for (int i = 0; i < item.size(); i++) {
                V3HomeBottomOneFragment fragment = new V3HomeBottomOneFragment();
                fragment.setData(item.get(i));
                fragments.add(fragment);
            }
        }


        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {

            return fragments.get(position);
        }
    }

    private class mTouchListener implements View.OnTouchListener {

        float x1 = 0;
        float x2 = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (currentPage == 2) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //当手指按下的时候
                        x1 = event.getX();
                        break;
                    case MotionEvent.ACTION_UP:
                        //当手指离开的时候
                        x2 = event.getX();
                        if (x1 - x2 > 50) {
                            if (pagerOne.getChildCount() != 0) {
                                pagerOne.setCurrentItem(0);
                            }

                        }
                        break;
                }
            }
            return false;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        getIndex();
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (refresh != null) {
            refresh.setEnabled(scrollView.getScrollY() == 0);
        }

    }

    @OnClick({R.id.btn_submit, R.id.txt_info_right, R.id.btn_wechat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                if (!Util.checkLogin(getActivity())) {
                    return;
                }

                if (!UserGlobal.getIsIdcardPass()) {
                    Dialog.gotoShiMing(getContext(), new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            Util.startActivity(getActivity(), V3IdcardIdentityActivity.class);
                        }

                        @Override
                        public void cancel() {

                        }
                    }).show();

                    return;
                }

                //0：失败、1：走新申请流程、2：继续上次未完成的流程、3：申请审核中、4：申请未通过、5：等待放款、6：还款中
                if (TextUtils.isEmpty(loanType)) {
                    getIndex();
                    return;
                }
                if (PreferenceUtils.getBoolean(getContext(), "is_locat", false)) {
                    switch (loanType) {
                        case "0":
                            break;
                        case "1":
                            EventBus.getDefault().post(new SelectMoneyEvent());
                            break;
                        case "2":
                            EventBus.getDefault().post(new SelectMoneyEvent());
                            break;
                        case "3":
                            break;
                        case "4":
                            Dialog.showCheckFail(getContext(), new Dialog.DialogClickListener() {
                                @Override
                                public void confirm() {
                                    EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                                }
                            });
                            break;
                        case "5":
                            break;
                        case "6":
                            ((MainActivityNew) getActivity()).getHuaKouInfo();
                            break;
                        case "7":
                            Intent intent = new Intent(getContext(), ServiceFeePayActivity.class);
                            intent.putExtra("deal_id", deal_id);
                            startActivity(intent);
                            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);

                            break;
                    }


                } else {
                    checkPermission(new PermissionActivity.CheckPermListener() {
                                        @Override
                                        public void superPermission() {
                                            PreferenceUtils.putBoolean(Application.getInstance(), "is_locat", true);
                                            ((MainActivityNew) getActivity()).initLocation();
                                        }
                                    }, R.string.location_p, R.string.get_location,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.READ_PHONE_STATE);
                }
                break;
            case R.id.txt_info_right:
                if (Util.checkLogin(getActivity()))
                    EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                break;
            case R.id.btn_wechat:
                Util.startActivity(getContext(), WechatChatActivity.class);
//                Util.startActivity(getContext(), V3IdcardIdentityActivity.class);
                break;
        }
    }
}
